#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
import re

from backend.app.core.path_conf import AvatarPath


def cut_path(path: str = AvatarPath, split_point: str = 'app') -> list:
    """
    切割路径

    :param path:
    :param split_point:
    :return:
    """
    after_path = path.split(split_point)
    return after_path


def complete_json(input_str):
    try:
        # 尝试解析输入字符串
        json.loads(input_str)
        return input_str  # 如果成功，返回原始字符串
    except json.JSONDecodeError as e:
        # 获取解析失败的位置和错误信息
        position = e.pos
        error_msg = str(e)

        # 分析错误信息，判断缺失的部分的类型
        if "Expecting property name enclosed in double quotes" in error_msg:
            # 缺失的部分是键，补全一个键
            missing_part = '"missing_key"'
        elif "Expecting ':'" in error_msg:
            # 缺失的部分是冒号，补全一个冒号
            missing_part = ':"missing_value"'
        elif "Expecting value" in error_msg:
            # 缺失的部分是值，补全一个值
            missing_part = '"missing_value"'
        else:
            # 其他情况，补全为 null
            missing_part = 'null'

        # 补全缺失的部分
        completed_json = input_str[:position] + missing_part + input_str[position:]
        return completed_json


def fixJSON(json_str):
    # Substitue all the backslash from JSON string.
    json_str = re.sub(r'\\', '', json_str)
    try:
        return json.loads(json_str)
    except ValueError:
        while True:
            # Search json string specifically for '"'
            b = re.search(r'[\w|"]\s?(")\s?[\w|"]', json_str)

            # If we don't find any the we come out of loop
            if not b:
                break

            # Get the location of \"
            s, e = b.span(1)
            c = json_str[s:e]

            # Replace \" with \'
            c = c.replace('"', "'")
            json_str = json_str[:s] + c + json_str[e:]
        return json.loads(json_str)
